#include "mainwidget.h"
#include <QFileDialog>
#include <QMessageBox>
#include <QIcon>
#include <QApplication>

QtWidgetsClass::QtWidgetsClass(QWidget* parent)
  : QWidget(parent)
  , m_vlayout(nullptr)
  , m_hlayout(nullptr)
  , m_select(nullptr)
  , m_txtedit(nullptr)
  , m_srcimage(nullptr)
{
  initUI();
  initSlots();
}

QtWidgetsClass::~QtWidgetsClass()
{
}

void QtWidgetsClass::initUI()
{
  QFile file(":/res/qss/transbutton.qss");
  if (file.open(QFile::ReadOnly)) {
    m_transQss = QLatin1String(file.readAll());
    file.close();
  }

  m_vlayout = new QVBoxLayout;
  m_hlayout = new QHBoxLayout;
  m_select = new QPushButton; 
  setTranBtnStyle(m_select, ":/res/icons/tiger.png", ":/res/icons/tigerBlack.png");
  m_select->setToolTip("select an image file");

  m_txtedit = new QTextEdit;
  m_srcimage = new QLineEdit;
  m_srcimage->setReadOnly(true);
  m_hlayout->addWidget(m_srcimage);
  m_hlayout->addWidget(m_select);

  m_vlayout->addLayout(m_hlayout);
  m_vlayout->addWidget(m_txtedit);

  setLayout(m_vlayout);
}

void QtWidgetsClass::initSlots()
{
  connect(m_select, &QPushButton::clicked, this, &QtWidgetsClass::onSelectClicked);
}

void QtWidgetsClass::setTranBtnStyle(QPushButton* button, QString normal, QString hover)
{
  QString stype = m_transQss.arg(normal).arg(hover);
  button->setStyleSheet(stype);
}

void QtWidgetsClass::onSelectClicked(bool clicked)
{
  QString imageFileName = QFileDialog::getOpenFileName(this, "open", "/", "Files(*.png)");
  if (QFile::exists(imageFileName))
    m_srcimage->setText(imageFileName);

  emit startConvert();

  QString destpath = m_srcimage->text();

  QFileInfo fileInfo(destpath);
  QString dir = fileInfo.dir().path();
  QString name = fileInfo.baseName();

  QString newPath = dir + "/" + name + ".ico";
  QImage img(imageFileName);
  if (img.save(newPath, "ICO"))
  {
    QMessageBox::information(this, "msg", "convert success");
  }
  else
  {
    QMessageBox::information(this, "msg", "convert failed");
  }
}

